#!/bin/bash
echo "请在UBUNTU下执行，在20.04和22.04两个版本测试通过"
echo "请确定是否打开源代码安装"
read -n 1
apt install -y make build-essential libelf-dev gcc g++ libssl-dev libncurses-dev flex bison \
binutils-dev cmake fonts-dejavu-core libfontconfig-dev \
gcc g++ pkg-config libegl-dev libgl-dev libgles-dev libspice-protocol-dev \
nettle-dev libx11-dev libxcursor-dev libxi-dev libxinerama-dev \
libxpresent-dev libxss-dev libxkbcommon-dev libwayland-dev wayland-protocols \
libpipewire-0.3-dev libpulse-dev libsamplerate0-dev  virt-manager qemu-system-x86 dkms \
mc vim network-manager-l2tp
cd /usr/src
apt source linux-headers-$(uname -r)

devicePciIds=$(lspci -nn | grep -i nvidia | awk '{print $1}')
declare -A deviceIds
for dev in $devicePciIds
do
	deviceIds[${#deviceIds[*]}]=$(lspci -n -s $dev | awk '{print $3}')
done
grubcmdline=" intel_iommu=on vfio-pci.ids=${deviceIds[0]},${deviceIds[1]}"
sedcmd="s/\(GRUB_CMDLINE_LINUX_DEFAULT=\".*\)\"/\1 $grubcmdline\"/"
echo $sedcmd
echo $sedcmd | xargs -0 -I {} sed '{}' /etc/default/grub > grub.txt
sed 's/#GRUB_GFXMODE=.*$/GRUB_GFXMODE=1920x1080/' grub.txt > grub
cp grub /etc/default/grub
rm grub.txt 

update-grub

cat > /etc/modprobe.d/nvidia.conf <<'EOF'
softdep nouveau pre: vfio-pci
softdep nvidia pre: vfio-pci
softdep nvidia* pre: vfio-pci
softdep snd_hda_intel pre: vfio-pci
EOF

cd ~
cat >/etc/modules-load.d/kvmfr.conf <<'EOF'
# KVMFR Looking Glass module
kvmfr
EOF

cat >/etc/udev/rules.d/99-kvmfr.rules<<'EOF'
SUBSYSTEM=="kvmfr", OWNER="liuwenyu", GROUP="kvm", MODE="0660"
EOF

cat >>/etc/apparmor.d/local/abstractions/libvirt-qemu <<'EOF'
# Looking Glass
/dev/kvmfr0 rw,
EOF

cat >/etc/modprobe.d/kvmfr.conf<<'EOF'
#KVMFR Looking Glass module
options kvmfr static_size_mb=128
EOF

cat >> /etc/libvirt/qemu.conf<<'EOF'

cgroup_device_acl = [
    "/dev/null", "/dev/full", "/dev/zero",
    "/dev/random", "/dev/urandom",
    "/dev/ptmx", "/dev/kvm",
    "/dev/kvmfr0"
]
EOF
apt install libspice-protocol-dev nettle-dev libfontconfig-dev libwayland-dev libxkbcommon-dev libx11-dev libxi-dev libxinerama-dev libxcursor-dev libxpresent-dev libxss-dev libegl-dev libgl-dev libpipewire-0.3-dev libpulse-dev libsamplerate0-dev
wget https://looking-glass.io/artifact/stable/source -O looking-glass-B6.tar.gz
tar zxfv looking-glass-B6.tar.gz
cd looking-glass-B6/client
mkdir build
cd build
cmake ../
make
make install

cd ../../module
make all
echo 请运行 gpuPassThrough2.sh path/to/linux/src 通常在/usr/src中

